import {baseUrl} from "./setting.js";


uni.setStorageSync("baseUrl",baseUrl);
const request = (options)=>{
	uni.showLoading();
	uni.onNetworkStatusChange(function(res){
		if(!res.isConnected){
			uni.showToast({
				title:"网络连接不可用",
				icon:"none"
			});
		};
		return false;
	});
	let token = uni.getStorageSync("token");
	return new Promise((resolve,reject)=>{
		uni.request({
			url:baseUrl + options.url,
			data:options.data,
			method:options.method,
			header:options.method.toLowerCase() === "get" ? {
				"X-Requested-With": "XMLHttpRequest",
				"Accept": "application/json",
				"Content-Type": "application/json; charset=UTF-8",
				"Authorization":"Bearer " + token
			} : {
				"X-Requested-With": "XMLHttpRequest",
				"Content-Type": "application/json; charset=UTF-8",
				"Authorization":"Bearer " + token
			},
			dataType:"json"
		}).then((res)=>{
			// console.log(res,"==========");
			uni.hideLoading();
			if(res.data.code === 401 || res.statusCode === 401){
				uni.showToast({
					title: '账号已过期，请重新登录',
					icon: 'none',
					complete: function() {
						uni.reLaunch({
							url:"/pages/login/index"
						});
						uni.clearStorageSync();
					}
				});
			}else{
				resolve(res.data);
			};
		}).catch((response)=>{
			// console.log(response)
			reject(response);
		});
	});
};

// 上传文件请求封装
const uploadFiles=(options)=>{
	uni.showLoading({
		title:"上传中......"
	});
	return new Promise((resolve,reject)=>{
		uni.uploadFile({
			url:baseUrl+options.url,
			filePath:options.filePath,
			name:options.name || "file",
			fileType:options.fileType || "image",
			header:options.header || {"Authorization" : "Bearer " + uni.getStorageSync("token")},
			timeout:options.timeout || 10000,
			formData:options.formData || {},
			success:(res)=>{
				uni.hideLoading();
				if(res.data.code === 401 || res.statusCode === 401){
					uni.showToast({
						title: '账号已过期，请重新登录',
						icon: 'none',
						complete: function() {
							uni.reLaunch({
								url:"/pages/login/index"
							});
							uni.clearStorageSync();
						}
					});
				}else{
					resolve(res.data);
				};
			},
			fail:(err)=>{
				reject(err);
			}
		});
	});
};

export {
	baseUrl,
	request,
	uploadFiles
};